package com.pb.camera;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import com.journeyapps.barcodescanner.CaptureActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.pb.camera.application.App;
import com.pb.camera.h264.PlayCurrentViewActivity;
import com.pb.camera.helper.JsonHelper;
import com.pb.camera.jph.activity.AddCameraNoticeActivity;
import com.pb.camera.jph.activity.SettingCameraWifiActivity;
import com.pb.camera.more.MoreActivity;
import com.pb.camera.utils.Constants;
import com.pb.camera.utils.Encryption;
import com.pb.camera.utils.JsonAnalyle;
import com.pb.camera.utils.MyTextWatcher;
import com.pb.camera.utils.RegexValidateUtil;
import com.pb.camera.utils.TaskHelper;
import com.pb.camera.utils.uniqueID;
import com.pb.camera.work.IOTCInit;
import com.pb.camera.work.ReceiveTask;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class LogInActivity extends Activity {
    private LinearLayout root;
    private EditText edit_account;
    private ImageView image_account;
    private ImageView image_weixin_log;
    private EditText edit_password;
    private String openId;
    private HttpUtils httpUtils = new HttpUtils();
    private TextView restartLog;
    private String account;
    private String password;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.arg2 == 6) {
                Toast.makeText(LogInActivity.this, (String) msg.obj,
                        Toast.LENGTH_SHORT).show();
            } else if (msg.arg2 == 8) {
                final View view = getLayoutInflater().inflate(
                        R.layout.log_fail_notification, null);
                TextView textMessage = (TextView) view
                        .findViewById(R.id.log_fail_reason);
                textMessage.setText(msg.obj.toString());
                restartLog = (TextView) view.findViewById(R.id.restart_log);
                restartLog.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        // 点击dialog里面的重新登录
                        v.setClickable(false);
                        click_login(0);
                    }
                });
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        LogInActivity.this);
                builder.setCancelable(true);
                AlertDialog dialog = builder.create();
                dialog.show();
                dialog.setContentView(view);
                WindowManager.LayoutParams lp = dialog.getWindow()
                        .getAttributes();
                // 另外加10的原因是处理padding的值
                lp.width = msg.arg1 + 20;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.CENTER;
                dialog.getWindow().setAttributes(lp);
            }
        }
    };
    private UMShareAPI mShareAPI;
    public ReceiveTask receiveTask;

    //private UMShareAPI mShareAPI;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login_activity);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        App.getInstance().getAllActivity().add(this);
        initView();
        // 初始化各个平台
        //configPlatforms();
        // default_log();
        // getArgument();
        //FIXME: delete it!
        ReceiveTask.getDefault().startReceiveTask(0);
        Intent intent = new Intent(LogInActivity.this, PlayCurrentViewActivity.class);
         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 初始化各个平台</br>
     */
    private void configPlatforms() {
        // 添加微信好友朋友圈
        addWXPlatform();
    }

    // 微信比较特别需要id等值
    private void addWXPlatform() {
        String appId = "wxdfaf4bec8994e3e2";
        String appSecret = "eaf915a543a7baa6596bce47da2ac490";
        PlatformConfig.setWeixin(appId, appSecret);
        mShareAPI = UMShareAPI.get(this);
        //SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;

/*		// 添加微信平台
        UMWXHandler wxHandler = new UMWXHandler(this, appId, appSecret);
		// 下面这句话会是的每次都会进入授权的界面
		wxHandler.setRefreshTokenAvailable(false);
		wxHandler.addToSocialSDK();
		// 支持微信朋友圈

		UMWXHandler wxCircleHandler = new UMWXHandler(this, appId, appSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();*/
    }

/*	*/

    /**
     * 根据平台登录</br>
     */
    private void login(final SHARE_MEDIA platform, final int id) {
        mShareAPI.doOauthVerify(this, platform, umAuthListener);
    }
	/*	mController.doOauthVerify(this, platform, new UMAuthListener() {
			@Override
			public void onStart(SHARE_MEDIA platform) {
				// 本处没有问题
			}

			@Override
			public void onError(SocializeException e, SHARE_MEDIA platform) {
				Toast.makeText(LogInActivity.this, "授权出错", Toast.LENGTH_LONG)
						.show();
			}

			@Override
			public void onCancel(SHARE_MEDIA platform) {
				// Toast.makeText(LogInActivity.this, "授权取消",
				// Toast.LENGTH_LONG).show();
			}

			@Override
			public void onComplete(Bundle arg0, SHARE_MEDIA arg1) {
				// TODO Auto-generated method stub
				String uid = arg0.getString("uid");
				if (!TextUtils.isEmpty(uid)) {
					// 获取用户的信息
					// 调用的位置
					getUserInfo(platform, id);
				} else {
					Toast.makeText(LogInActivity.this, "获取信息失败",
							Toast.LENGTH_SHORT).show();
				}
			}
		});*/

    /**
     * 获取用户信息</br>
     *//*
	private void getUserInfo(SHARE_MEDIA platform, final int id) {
		mController.getPlatformInfo(this, platform, new UMDataListener() {
			private Gson gson;

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
			}

			@Override
			public void onComplete(int arg0, Map<String, Object> info) {
				// TODO Auto-generated method stub
				if (info != null) {
					gson = new Gson();
					String json = gson.toJson(info);
					// id=2代表是微信登录.方便以后的扩充
					if (id == 2) {
						WeixinInfo weixinInfo = gson.fromJson(json,
								WeixinInfo.class);
						// openid 含有非法字符码
						openId = weixinInfo.getOpenid();
						Log.i("===", "openid" + openId);
						getCode(Constants
								.check_if_weixin_and_account_binded(urlEncode(weixinInfo
										.getOpenid())), LogInActivity.this, 0);
						// 上传微信的信息,upInfo(weixinInfo);
					}
				}
			}
		});
	}*/
    private void initView() {

        root = (LinearLayout) findViewById(R.id.log_linear_rootview);
        edit_account = (EditText) findViewById(R.id.log_edit_account);
        image_account = (ImageView) findViewById(R.id.log_image_reset_account);
        edit_password = (EditText) findViewById(R.id.log_edit_password);
        ImageView image_password = (ImageView) findViewById(R.id.log_image_reset_password);
        edit_account.addTextChangedListener(new MyTextWatcher(edit_account,
                image_account));
        edit_password.setTag("1");
        edit_password.addTextChangedListener(new MyTextWatcher(edit_password,
                image_password));
        ImageView image_see_pasword = (ImageView) findViewById(R.id.log_image_see_password);
        image_see_pasword.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (edit_password.getTag().equals("1")) {
                    v.setSelected(true);
                    // 显示密码
                    edit_password
                            .setTransformationMethod(HideReturnsTransformationMethod
                                    .getInstance());
                    edit_password.setTag("2");
                } else {
                    v.setSelected(false);
                    edit_password
                            .setTransformationMethod(PasswordTransformationMethod
                                    .getInstance());
                    edit_password.setTag("1");
                }
                edit_password.postInvalidate();
                CharSequence charSequence = edit_password.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }
            }
        });
        image_weixin_log = (ImageView) findViewById(R.id.log_image_weiixn_log);

    }

    public void log_onClick(View view) {
        switch (view.getId()) {
            case R.id.log_linear_rootview:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                break;
            // 登录
            case R.id.log_linear_log_in:
                // 正常登陆
                click_login(1);
                break;
            case R.id.log_image_weiixn_log:
                // 微信登录
                login(SHARE_MEDIA.WEIXIN, 2);
                break;
            // 忘记密码
            case R.id.log_text_fortgetpassword:
                Bundle bundle1 = new Bundle();
                bundle1.putString("log_or_find", "find");
                Intent intent1 = new Intent();
                // intent1.setClass(this, VerrificationCodeActivity.class);
                intent1.putExtras(bundle1);
                startActivity(intent1);
                break;
            // 注册
            case R.id.log_text_log:
                Bundle bundle = new Bundle();
                bundle.putString("log_or_find", "log");
                Intent intent = null;
                // new Intent(LogInActivity.this,VerrificationCodeActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
        }
    }

    private void click_login(int mode) {
        if (mode == 1) {
            if (RegexValidateUtil.checkName(edit_password.getText().toString())) {
                String account = edit_account.getText().toString();
                // 内部包含对于url是非法的字符
                String password = Encryption.encode(edit_password.getText()
                        .toString());
                getCode(Constants.login(account, urlEncode(password),
                        uniqueID.id(this), ""), this, 1);
            } else {
                Toast.makeText(this, "密码格式不对", Toast.LENGTH_SHORT).show();
            }
        } else if (mode == 0) {
            // 这是
            SharedPreferences pre = getSharedPreferences("itisforlife",
                    Context.MODE_PRIVATE);
            account = pre.getString("account", "default");
            password = pre.getString("password", "default");
            edit_account.setText(account);
            edit_password.setText("******");

            getCode(Constants.login(account, password, uniqueID.id(this), ""),
                    this, 2);
        }
    }

    private void getCode(String url, final Activity activity, final int mode) {
        httpUtils.send(HttpMethod.POST, url, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Toast.makeText(activity, "网络访问失败,请检查你的网络", Toast.LENGTH_SHORT).show();
                if (restartLog != null) {
                    restartLog.setClickable(true);
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                Log.i("123", "返回的用户名" + arg0.result);
                boolean flag = JsonAnalyle.jsonAnalyse(arg0.result,
                        LogInActivity.this, null, handler);
                // 返回true
                if (flag) {
                    if (mode == 1) {
                        // 使用账户密码登录成功保存最新的账户名
                        // 保存的账户密码都是加密完了的,但是openid没有用urlEncode加密
                        Map map = JsonAnalyle.logSuccess(arg0.result);
                        String password = Encryption.encode(edit_password
                                .getText().toString());
                        saveUserMessage((String) map.get("account"), password,
                                (String) map.get("gesture"),
                                (String) map.get("userid"),
                                (String) map.get("email"),
                                (String) map.get("mobile"),
                                (String) map.get("openid"), 0);
                        updateAppUserInfo((String) map.get("account"),
                                password, (String) map.get("gesture"),
                                (String) map.get("userid"),
                                (String) map.get("email"),
                                (String) map.get("mobile"),
                                (String) map.get("openid"));
                        String gesture = (String) map.get("gesture");
                        if (gesture == null || gesture.equals("")
                                || gesture.equals("default")) {
                            // 在微信上面注册成功之后,但是没有设置手势
                            // 在app上面,使用手机号登录,需要检查是否设置手势
                            // 若是没有的话需要开启创建手势界面
                            Bundle bundle = new Bundle();
                            bundle.putString("whereFrom",
                                    "only_register_gesture");
                            bundle.putString("userId",
                                    (String) map.get("userid"));
                            Intent intentGesture = new Intent();
                            intentGesture.putExtras(bundle);
                            intentGesture.setClass(LogInActivity.this,
                                    CreateGesturePasswordActivity.class);
                            startActivity(intentGesture);
                        } else {
                            Intent intent0 = new Intent();
                            intent0.setClass(LogInActivity.this,
                                    HomePageActivity.class);
                            intent0.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent0);
                            finish();
                        }

                    } else if (mode == 0) {
                        // 微信已经绑定到别的账号了
                        // 相当于使用别的账号重新登录了一遍
                        Map map = JsonAnalyle.ifWeiXinbinded(arg0.result);
                        SharedPreferences pre = getSharedPreferences(
                                "itisforlife", Context.MODE_PRIVATE);
                        // 保存到本地
                        saveUserMessage((String) map.get("acco"),
                                (String) map.get("p"),
                                (String) map.get("gesture"),
                                (String) map.get("userid"),
                                (String) map.get("email"),
                                (String) map.get("mobile"),
                                (String) map.get("openid"), 0);
                        // 保存到application
                        updateAppUserInfo((String) map.get("acco"),
                                (String) map.get("p"),
                                (String) map.get("gesture"),
                                (String) map.get("userid"),
                                (String) map.get("email"),
                                (String) map.get("mobile"),
                                (String) map.get("openid"));
                        // App.getInstance().getLockPatternUtils().saveLockPattern(App.getInstance().getLockPatternUtils().stringToPattern((String)map.get("gesture")));
                        // 输入手势验证是否一致
                        Intent intent = new Intent(LogInActivity.this,
                                UnlockGesturePasswordActivity.class);
                        startActivity(intent);
                    } else if (mode == 2) {
                        // 点击对话框里面的重新登录
                        Map map = JsonAnalyle.logSuccess(arg0.result);
                        saveUserMessage((String) map.get("account"), password,
                                (String) map.get("gesture"),
                                (String) map.get("userid"),
                                (String) map.get("email"),
                                (String) map.get("mobile"),
                                (String) map.get("openid"), 1);
                        updateAppUserInfo((String) map.get("account"),
                                password, (String) map.get("gesture"),
                                (String) map.get("userid"),
                                (String) map.get("email"),
                                (String) map.get("mobile"),
                                (String) map.get("openid"));
                        Intent intent2 = new Intent();
                        intent2.setClass(LogInActivity.this,
                                HomePageActivity.class);
                        intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent2);
                        if (restartLog != null) {
                            restartLog.setClickable(true);
                        }
                        finish();
                    }
                }
                // 返回false的时候
                else if (!flag) {
                    if (mode == 2 && restartLog != null) {
                        restartLog.setClickable(true);
                    }
                    if (mode == 0) {
                        // 微信登录成功但是该微信号没有绑定或者要去注册账号
                        Map map = JsonHelper.jsonStringToMap(arg0.result,
                                new String[]{"errcode"}, null);
                        if (((String) map.get("errcode")).equals("50006")) {
                            View view = getLayoutInflater().inflate(
                                    R.layout.weixin_log_dialog, null);
                            TextView text_no = (TextView) view
                                    .findViewById(R.id.weiixn_log_dialog_no);
                            text_no.setClickable(true);
                            text_no.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    // TODO Auto-generated method stub
                                    // 注册账号
                                    Bundle bundle = new Bundle();
                                    bundle.putString("openId", openId);
                                    Intent intent = new Intent(
                                            LogInActivity.this,
                                            WeiXinRegisterActivity.class);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }
                            });
                            TextView text_yes = (TextView) view
                                    .findViewById(R.id.weiixn_log_dialog_yes);
                            text_yes.setClickable(true);
                            text_yes.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    // TODO Auto-generated method stub
                                    // 绑定账号
                                    Bundle bundle = new Bundle();
                                    bundle.putString("openId", openId);
                                    Intent intent = new Intent(
                                            LogInActivity.this,
                                            WeiXinBindActivity.class);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }
                            });
                            AlertDialog.Builder builder = new AlertDialog.Builder(
                                    LogInActivity.this);
                            builder.setView(view);
                            Dialog dialog = builder.create();
                            dialog.setCanceledOnTouchOutside(true);
                            dialog.show();
                        }
                    }
                }
            }

        });
    }

    /**
     * @param account
     * @param password 密码只有在用户手动输入的时候使用ur转码然后保存,从sp取出来之后不用再url转码了,不然两次url转码铁定出错的
     * @param gesture
     * @param userId
     * @param email
     * @param mobile
     * @param openId
     */
    private void updateAppUserInfo(String account, String password,
                                   String gesture, String userId, String email, String mobile,
                                   String openId) {
        App application = App.getInstance();
        application.setAccount(account);
        application.setPassword(urlEncode(password));
        application.setOpenId(openId);
        application.setGesture(gesture);
        application.setMobile(mobile);
        application.setEmail(email);
        application.setUserId(userId);
    }

    /**
     * @param account
     * @param password 密码只有在用户手动输入的时候使用ur转码然后保存,从sp取出来之后不用再url转码了
     * @param gesture
     * @param userId
     * @param email
     * @param mobile
     * @param openId
     * @param mode     代表的是 是否对密码url加密
     */
    private void saveUserMessage(String account, String password,
                                 String gesture, String userId, String email, String mobile,
                                 String openId, int mode) {

        SharedPreferences pre = getSharedPreferences("itisforlife",
                Context.MODE_PRIVATE);
        Editor editor = pre.edit();
        editor.putString("account", account);
        // 密码不在返回之内列
        if (mode == 0) {
            editor.putString("password", urlEncode(password));
        } else if (mode == 1) {
            editor.putString("password", password);
        }
        editor.putString("gesture", gesture);
        editor.putString("openid", openId);
        editor.putString("email", email);
        editor.putString("userid", userId);
        editor.putString("mobile", mobile);
        editor.commit();
    }

    private String urlEncode(String data) {
        String outcome = null;
        try {
            outcome = URLEncoder.encode(data, "utf-8");
            Log.i("===", outcome);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            Log.i("===", "编码错误");
            e.printStackTrace();
        }
        return outcome;
    }

    // //极光推送的统计代码
    // @Override
    // protected void onResume() {
    // JPushInterface.onResume(this);
    // super.onResume();
    // }
    // @Override
    // protected void onPause() {
    // JPushInterface.onPause(this);
    // super.onPause();
    // }

    /**
     * 测量dialog的大小
     *
     * @param errcodeMesage
     */
    private void craeteDialog(final String errcodeMesage) {
        final View view1 = getLayoutInflater().inflate(
                R.layout.log_fail_notification, null);
        final TextView textMessage = (TextView) view1
                .findViewById(R.id.log_fail_reason);
        textMessage.setText(errcodeMesage);
        final TextView restartLog = (TextView) view1
                .findViewById(R.id.restart_log);
        root.addView(view1);
        view1.getViewTreeObserver().addOnPreDrawListener(
                new OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        // TODO Auto-generated method stub
                        view1.getViewTreeObserver().removeOnPreDrawListener(
                                this);

                        int meWidth = textMessage.getWidth();
                        int logWidth = restartLog.getWidth();
                        int width = 10;
                        if (meWidth >= logWidth) {
                            width = meWidth;
                        } else {
                            width = logWidth;
                        }
                        root.removeView(view1);
                        Message message = Message.obtain();
                        message.arg2 = 8;
                        message.arg1 = width;
                        message.obj = errcodeMesage;
                        handler.sendMessage(message);
                        return true;
                    }
                });
        // //
    }

    /**
     * 自动登录失败,弹出的提示
     */
    private void getArgument() {
        String whereFrom = getIntent().getExtras().getString("whereFrom");
        if (whereFrom.equals("restart")) {
        } else if (whereFrom.equals("welcome")) {
            return;
        } else {
            String errorMessage = getIntent().getExtras().getString(
                    "errorMessage");
            if (errorMessage != null && !errorMessage.equals("0")) {
                if (errorMessage.equals("1")) {
                    // 代表的是解锁页面跳过来的
                    // 用户忘记手势,使用密码登录
                } else {
                    // 代表load界面跳转过来的,自动登录的时候报错
                    // 例如在另一个app上面登录了,网络异常等
                    craeteDialog(errorMessage);
                }
            }
        }

    }

    @Override
    public void finish() {
        App.getInstance().getAllActivity().remove(this);
        super.finish();
    }

    @Override
    protected void onDestroy() {
        App.getInstance().getAllActivity().remove(this);
        super.onDestroy();
    }

    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(getApplicationContext(), "Authorize succeed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getApplicationContext(), "Authorize fail", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getApplicationContext(), "Authorize cancel", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }
}
